/**
 * 微博超话自动签到插件 V1.5
 * Created by MapleX
 * content.js - 内容脚本
 */

// 滚动到底部加载所有超话
async function scrollToLoadAll() {
  return new Promise((resolve) => {
    let lastHeight = document.documentElement.scrollHeight;
    let scrollAttempts = 0;
    const maxAttempts = 10; // 最大尝试次数
    
    function scroll() {
      window.scrollTo(0, document.documentElement.scrollHeight);
      setTimeout(() => {
        const newHeight = document.documentElement.scrollHeight;
        if (newHeight > lastHeight && scrollAttempts < maxAttempts) {
          // 高度变化，说明加载了新内容
          lastHeight = newHeight;
          scrollAttempts++;
          scroll();
        } else {
          // 高度不变或达到最大尝试次数，认为已加载完成
          window.scrollTo(0, 0); // 滚回顶部
          resolve();
        }
      }, 2000); // 等待2秒让新内容加载
    }
    
    scroll();
  });
}

function autoCheckIn() {
  const checkInButton = document.querySelector('a[action-type="widget_take"]');
  const superTopicId = window.location.href.match(/\/p\/(\d+)/)?.[1];
  const superTopicName = document.querySelector('.username')?.textContent?.trim();
  
  if (checkInButton) {
    const buttonText = checkInButton.querySelector('span')?.textContent?.trim();
    
    if (buttonText === '签到') {
      checkInButton.click();
      chrome.storage.local.set({ 
        status: '签到成功！'
      });
    } else if (buttonText === '已签到') {
      // 不设置状态
    }
  } else {
    chrome.storage.local.set({ 
      status: '未找到签到按钮'
    });
  }
}

async function getAllSuperTopics() {
  // 先滚动加载所有超话
  await scrollToLoadAll();
  
  // 然后获取所有超话链接
  const superTopicLinks = document.querySelectorAll('a.ALink_none_1w6rm.TopicFeedCard_left_EgdGf');
  const foundTopics = Array.from(superTopicLinks).map(link => {
    return {
      url: link.getAttribute('href').startsWith('//') ? 
        'https:' + link.getAttribute('href') : link.getAttribute('href'),
      name: link.querySelector('.TopicFeedCard_cla_1pQ6t')?.textContent?.trim() || '未知超话'
    };
  }).filter(topic => topic.url);
  
  if (foundTopics.length > 0) {
    console.log('找到超话：', foundTopics.length, '个');
    // 保存检索到的超话
    chrome.storage.local.set({ foundTopics });
    // 发送链接给 background 处理
    chrome.runtime.sendMessage({
      action: 'processSuperTopics',
      urls: foundTopics.map(topic => topic.url)
    });
  } else {
    console.log('未找到超话链接');
    chrome.storage.local.set({ foundTopics: [] });
  }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'checkIn') {
    autoCheckIn();
  } else if (request.action === 'getAllSuperTopics') {
    getAllSuperTopics();
  } else if (request.action === 'getTopicTitle') {
    setTimeout(() => {
      const title = document.querySelector('.username')?.textContent?.trim();
      console.log('获取到超话标题:', title);
      sendResponse({ title: title });
    }, 3000);
  }
  return true;
}); 